<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身会员购课开课记录查询</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/badge.css') }}">
    <style>
        .valid-inner-box{
            font-size:12px;
            color:#428f56;
            border:1px solid #428f56;
            border-radius:4px;
            padding:6px;
            margin-top:4px;
            margin-bottom:4px;                    
            text-align:left;
        }
        .ctn-inner-box{
            font-size:12px;
            background-color: #333d66;
            color:#fbfcfd;
            border:1px solid #333d66;
            border-radius:4px;
            padding:6px;
            margin-top:4px;
            margin-bottom:4px;                    
            text-align:left;
            line-height: 24px;

        }
        
    </style>

</head>
<body>
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>购课开课记录查询</h2>
    <div>
        <div class="form-row"><h4 style="width:70px;">会员姓名</h4><input id="cusName" style="width: 100px;" oninput="handleInput()"></div>
        <div id="cusList" style="display: none;"></div>
            
        
    <hr>

    <div id="validSummary" style="margin-top:20px;"> </div>
    <div id="notOpenSummary" style="margin-top:20px;"> </div>

    <div id='dateBox' class="form-row" style="display:none;"><h4 style="width:100px;">选择购课日期</h4><select id="dateSel"></select></div>    

    <div id="buyList" style="margin-top:20px;"></div>

        
    </div>


    <script src="../static/js/common.js"></script>
    <script>
        let cus_list;
        let ins_list;
        let buyData;
        let sexStr;
        let cusTotalAmount=0;
        

        document.addEventListener("DOMContentLoaded",function(){
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];



            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log('cus list:',data);
                cus_list=data;
                  })
                .catch(error => console.error('Error:', error));

                fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);


                 })
                .catch(error => console.error('Error:', error));


                getCusStageConfig();



           
        });

        function showCusStage(totalAmount,n){
            const ranges = Object.keys(cusStageConfig);
            let range = null;
            for (const rangeKey of ranges) {
            const [min, max] = rangeKey.split('-').map(Number);
            if (Math.round(totalAmount/10) >= Math.round(min/10) && Math.round(totalAmount/10) < Math.round(max/10)) {
                range = cusStageConfig[rangeKey];
                console.log('所在的range：',range);
                break;
            }
            }

            // 根据会员等级显示相应的勋章
            let badgeClass = '';
            let badgeText = range.name;
            
            switch(range.name) {
                case '心动行动':
                    badgeClass = 'badge badge-bronze';
                    break;
                case '渐入佳境':
                    badgeClass = 'badge badge-silver';
                    break;
                case '身体力行':
                    badgeClass = 'badge badge-gold';
                    break;
                case '知行合一':
                    badgeClass = 'badge badge-platinum badge-glow';
                    break;
                default:
                    badgeClass = 'badge badge-bronze';
            }

            

            document.getElementById(`stage_${n}`).innerHTML=`<span style='font-size:10px;font-weight:bold;'>${range.star} @ ${Math.round(cusTotalAmount/10)}分</span>`;
            document.getElementById(`stage_${n}`).style.fontSize='14px';
            if(range.star && ['二星会员','三星会员','四星会员'].includes(range.star)){
                document.getElementById(`stage_${n}`).innerHTML=`<div style="line-height:1.2;margin:0;padding:0;text-align:center;"><div style='font-size:10px;font-weight:bold;'>${range.star} @ ${Math.round(cusTotalAmount/10)}分</div><div style="font-size:10px;margin:0;padding:2px;color:#ff6b35;font-weight:bold;">购课即享优惠</div></div>`;
                document.getElementById(`offsetAmount_${n}`).innerHTML=`<div style='font-size:9px;text-align:center;'><div>单笔实际消费满${range.offset_limit}元</div><div>立减${range.offset_amount}元</div></div>`;
            }
            document.getElementById(`badge_${n}`).innerHTML=`<div class="${badgeClass}" style='margin-top:8px;'>${badgeText}勋章</div>`;
        
            
        }

        function showStageHints(cusTotalAmount){
            // console.log('积分：',Math.round(cusTotalAmount/10));
            if(Math.round(cusTotalAmount/10)<570){
                document.getElementById('firstStageHint').innerHTML=`<span style='font-size:12px;color:#dbbe94;'>您还需要<span style='font-weight:bold;'>${570-Math.round(cusTotalAmount/10)}</span>积分即可升级为二星会员，享受购课立减福利。</span>`;
            }else if(Math.round(cusTotalAmount/10)<950){
                document.getElementById('firstStageHint').innerHTML=`<span style='font-size:12px;color:#dbbe94;'>您还需要<span style='font-weight:bold;'>${950-Math.round(cusTotalAmount/10)}</span>积分即可升级为三星会员，享受更多购课立减福利。</span>`;
            }else if(Math.round(cusTotalAmount/10)<1300){
                document.getElementById('firstStageHint').innerHTML=`<span style='font-size:12px;color:#dbbe94;'>您还需要<span style='font-weight:bold;'>${1300-Math.round(cusTotalAmount/10)}</span>积分即可升级为四星会员，享受钜惠购立减福利。</span>`;
            }else if(Math.round(cusTotalAmount/10)<100000){
                document.getElementById('firstStageHint').innerHTML='';
            }else{
                document.getElementById('firstStageHint').innerHTML='';
            }
        }


        function getCusStageConfig(){
            fetch('/get_cus_stage_config', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {                
                cusStageConfig=data.stage_config;
                console.log('cusStageConfig list:',cusStageConfig);
                  })
                .catch(error => console.error('Error:', error)); 

        }


        function get_cus_continue_buy(){
            const cusIdName=document.getElementById('cusName').value.trim();
            fetch('/get_cus_continue_buy', {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json'
                    },
                    body:JSON.stringify({'cusIdName':cusIdName})
            })
            .then(response=>response.json())
            .then(data=>{
                console.log('cus continue buy data:',data);       
                
                if(data['res']==='ok'){
                    console.log(data['data'],data['latest_3_times_continue_buy'])
                }
            })
            .catch(error=>console.log(error));
        }


        function formatTimeRange(timeStr) {
            // 1. 分割字符串，获取开始和结束时间
            const [start, end] = timeStr.split('-');
            
            // 2. 格式化时间（补全冒号）
            const formatTime = (time) => {
                const hours = time.slice(0, 2);  // 取前两位作为小时
                const minutes = time.slice(2);   // 取后两位作为分钟
                return `${hours}:${minutes}`;
            };
            
            // 3. 拼接成最终格式
            return `${formatTime(start)}-${formatTime(end)}`;
            }

        function showBuyRecDetail(){
            // console.log('buy data:',buyData);
            const cusIdName=document.getElementById('cusName').value;
            const dateSel=document.getElementById('dateSel').value;
            const buyList=document.getElementById('buyList');

            buyList.innerHTML='';

            

            if(Object.keys(buyData).length>0){      
                let nn=1;          
                const buyTitle=document.createElement('div');
                sexStr=buyData[0]['sex']==='男'?'先生':'女士';
                buyTitle.innerHTML=`
                    <div style='margin-bottom:20px;margin-top:20px;text-align:center;font-size:16px;font-weight:bold;'>${cusIdName.slice(7)+sexStr}购课及开课记录</div>
                `
                buyList.appendChild(buyTitle);
               
                for(const n in buyData){
                    // const divDtl=document.createElement('div');
                    if(dateToStringGmt(buyData[n]['buy_date'],'date')===dateSel){                           
                        let cmtStr = '';

                    // 1. 处理支付相关备注
                    if (parseFloat(buyData[n]['real_pay']) < parseFloat(buyData[n]['pay'])) {
                        // 优惠数 >1 为代金券，0-1 之间为折扣券
                        if (parseFloat(buyData[n]['used_vc_amount']) >= 1) {
                            // 代金券逻辑
                            if (parseFloat(buyData[n]['real_pay']) + parseFloat(buyData[n]['used_vc_amount']) < parseFloat(buyData[n]['pay'])) {
                                if(buyData[n]['cons_with_pay']==='no'){
                                    cmtStr = `余款${parseFlcat(buyData[n]['pay']) - parseFloat(buyData[n]['real_pay']) - parseFloat(buyData[n]['used_vc_amount'])}元未支付`;
                                }else{
                                    cmtStr = `用优惠券支付${buyData[n]['used_vc_amount']}元`;
                                }
                            } else {
                                cmtStr = `已用优惠券支付${buyData[n]['used_vc_amount']}元`;
                                if (buyData[n]['use_for'] === 'deposit') {
                                    cmtStr = `已支付过定金${buyData[n]['used_vc_amount']}元`;
                                }
                            }
                        } else if (parseFloat(buyData[n]['used_vc_amount']) < 1 && parseFloat(buyData[n]['used_vc_amount']) > 0) {
                            // 折扣券逻辑
                            if (parseFloat(buyData[n]['real_pay']) < parseFloat(buyData[n]['used_vc_amount']) * parseFloat(buyData[n]['pay'])) {
                                if(buyData[n]['cons_with_pay']==='no'){
                                    cmtStr = `余款${parseFloat(buyData[n]['used_vc_amount']) * parseFloat(buyData[n]['pay']) - parseFloat(buyData[n]['real_pay'])}元未支付`;
                                }else{
                                    cmtStr = ``;
                                }
                            } else {
                                cmtStr = '';
                            }
                        } else {
                            // 无优惠券情况
                            if(buyData[n]['cons_with_pay']==='no'){
                                cmtStr = `余款${buyData[n]['pay'] - buyData[n]['real_pay']}元未支付`;
                            }else{
                                cmtStr= '';
                            }
                        }
                    }

                    // 2. 存储所有备注片段（避免直接拼接字符串）
                    const commentParts = [];

                    // 如果 cmtStr 不为空，先加入数组
                    if (cmtStr) {
                        commentParts.push(cmtStr);
                    }

                    // 3. 处理共同持卡人（如果有）
                    if (buyData[n]['co_holder']?.includes(',')) {
                        let coArr = buyData[n]['co_holder'].split(',');
                        coArr = coArr.map(co => co.substring(7)); // 去掉前7个字符（假设是固定格式）
                        const newCoArr = coArr.join('，'); // 用中文逗号连接
                        commentParts.push(`共同持卡人：${newCoArr}`);
                    }

                    // 4. 处理 cmt 字段（按 | 分隔，并检查是否包含“转换”或“月卡”）
                    if (buyData[n]['cmt']) {
                        const cmtItems = buyData[n]['cmt'].split('|').filter(item => item.trim()); // 按 | 分隔并过滤空值
                        for (const item of cmtItems) {
                            // 仅显示包含特殊字段的信息
                            // if (item.includes('转换')) {
                            //     commentParts.push(item);
                            // }
                            // if (item.includes('月卡')) {
                            //     commentParts.push(item);
                            // }
                            
                            // 显示所有的备注信息，不需要显示的信息在管理员备注中。
                            commentParts.push(item);
                        }
                    }

                    // 6. 最终拼接逻辑（用分号分隔，避免句首分号）
                    if (commentParts.length > 0) {
                        cmtStr = commentParts.join(' | '); // 使用|分隔
                        // 确保不会出现 `；xxx` 的情况（理论上不会，但保险起见）
                        if (cmtStr.startsWith('；')) {
                            cmtStr = cmtStr.substring(1);
                        }
                    } else {
                        cmtStr = ''; // 如果没有任何备注，保持空字符串
                    }

                        let clsDays=buyData[n]['buy_cls_days']>900?'-':buyData[n]['buy_cls_days']+' 天';

                        let clsStatus;
                        if(buyData[n]['buy_type']==='限时课程'){
                            if(buyData[n]['card_start_time']==='-' && buyData[n]['end_time']==='-'){
                                clsStatus='未开课，请教练为你开课。';
                            }else{
                                const today=new Date();
                                today.setHours(0,0,0,0);

                                const startDate=new Date(buyData[n]['card_start_time']);
                                startDate.setHours(0,0,0,0);

                                const endDate=new Date(buyData[n]['end_time']);
                                endDate.setHours(0,0,0,0);

                                // console.log(startDate,endDate);

                                if(today<startDate && today<endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    clsStatus=`已开课，课程未开始。<br>有效期 ${buyData[n]['card_start_time']} 至 ${dateToString(showEndDate,'date')}`;
                                }else if(today>=startDate && today<endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    clsStatus=`已开课，课程生效中。已上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节。<br>有效期 ${buyData[n]['card_start_time']} 至 ${dateToString(showEndDate,'date')}`;
                                    //处于有效期中的课程是否已上完结束
                                    if(parseInt(buyData[n]['cls_qty'])-parseInt(buyData[n]['cls_tkn_qty'])<=0){                                       
                                        clsStatus=`课程已完成${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节失效<br>有效期 ${dateToString(startDate,'dateDot')}-${dateToString(showEndDate,'dateDot')}`;
                                    }
                                
                                }else if(today>startDate && today>=endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    clsStatus=`课程已过期失效\n<br>(${dateToString(startDate,'dateDot')}-${dateToString(showEndDate,'dateDot')}  上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节)`;
                                } 

                               
                            }
                        //常规课程
                        }else{                            
                            if(buyData[n]['buy_cls_name']==='9.9元私教'){
                                const today=new Date();
                                today.setHours(0,0,0,0);

                                const startDate=new Date(buyData[n]['card_start_time']);
                                startDate.setHours(0,0,0,0);

                                const endDate=new Date(buyData[n]['end_time']);
                                endDate.setHours(0,0,0,0);
                                if(today>=startDate && today<endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    if(parseInt(buyData[n]['cls_tkn_qty'])>=parseInt(buyData[n]['cls_qty'])){
                                        clsStatus=`课程已失效。上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节。<br>有效期 ${buyData[n]['card_start_time']} 至 ${dateToString(showEndDate,'date')}`;
                                    }else{
                                        clsStatus=`课程生效中。已上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节。<br>有效期 ${buyData[n]['card_start_time']} 至 ${dateToString(showEndDate,'date')}`;
                                    }
                                    
                                }else if(today>startDate && today>=endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    clsStatus=`课程已过期失效\n<br>(${dateToString(startDate,'dateDot')}-${dateToString(showEndDate,'dateDot')}  上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节)`;
                                } 

                            }else if(buyData[n]['buy_cls_name']==='活动赠课'){
                                clsDays='-';
                                const today=new Date();
                                today.setHours(0,0,0,0);

                                const startDate=new Date(buyData[n]['card_start_time']);
                                startDate.setHours(0,0,0,0);

                                const endDate=new Date(buyData[n]['end_time']);
                                endDate.setHours(0,0,0,0);
                                if(today>=startDate && today<endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    if(parseInt(buyData[n]['cls_tkn_qty'])>=parseInt(buyData[n]['cls_qty'])){
                                        clsStatus=`课程已失效。上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节。<br>有效期 ${buyData[n]['card_start_time']} 至 ${dateToString(showEndDate,'date')}`;
                                    }else{
                                        clsStatus=`课程生效中。已上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节。<br>有效期 ${buyData[n]['card_start_time']} 至 ${dateToString(showEndDate,'date')}`;
                                    }
                                    
                                }else if(today>startDate && today>=endDate){
                                    const showEndDate=new Date(buyData[n]['end_time']);
                                    showEndDate.setDate(showEndDate.getDate()-1);
                                    clsStatus=`课程已过期失效\n<br>(${dateToString(startDate,'dateDot')}-${dateToString(showEndDate,'dateDot')}  上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节)`;
                                } 
                            }else{
                                if(parseInt(buyData[n]['cls_qty'])>buyData[n]['cls_tkn_qty']){
                                    clsStatus=`有效，已上了${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节。`;
                                }else{
                                    clsStatus=`课程已上完失效（${buyData[n]['cls_tkn_qty']}/${parseInt(buyData[n]['cls_qty'])}节）。`
                                }
                            }
                        }

                        // 约课时段
                        let validTimeHtml='正常营业时间';
                        if(buyData[n]['valid_time']==='all_day'){
                            validTimeHtml=`正常营业时间`;
                        }else{
                            validTimeHtml=`<span style='font-weight:bold;color:red;'>${formatTimeRange(buyData[n]['valid_time'])}</span>`;
                            
                        }

                        const divRes=document.createElement('div');
                        divRes.innerHTML=`
                            <div id="show-cus-buy-detail-box">
                                <div style="display:block;">
                                    <div style="display:flex;margin:4px;"><span class="small-title">序号</span><span class="small-buy-list-content" style="margin-left:10px;">${nn}</span></div>
                                    <div style="display:flex;margin:4px;"><span class="small-title">购课日期</span><span class="small-buy-list-content">${dateToStringGmt(buyData[n]['buy_date'],'date')}</span></div>
                                    <div style="display:flex;margin:4px;align-items:center;jusify-content:center;"><span class="small-title">流水号</span><span class="small-buy-list-content" style="font-size:10px;">${buyData[n]['buy_flow_id']}</span></div>  
                                    <div style="display:flex;margin:4px;"><span class="small-title">课程类型</span><span class="small-buy-list-content">${buyData[n]['buy_type']}</span></div>                                
                                    <div style="display:flex;margin:4px;"><span class="small-title">课程名称</span><span class="small-buy-list-content">${buyData[n]['buy_cls_name']}</span></div>
                                    <div style="display:flex;margin:4px;"><span class="small-title">课程节数</span><span class="small-buy-list-content">${parseInt(buyData[n]['cls_qty'])} 节</span></div>
                                    <div style="display:flex;margin:4px;"><span class="small-title">课程天数</span><span class="small-buy-list-content">${clsDays}</span></div>
                                    <div style="display:flex;margin:4px;"><span class="small-title">约课时段</span><span class="small-buy-list-content">${validTimeHtml}</span></div>
                                    <div style="display:flex;margin:4px;"><span class="small-title">实付金额</span><span class="small-buy-list-content">${buyData[n]['real_pay']} 元</span></div>
                                    <div style="display:flex;margin:4px;align-items:center;jusify-content:center;"><span class="small-title">课程状态</span><span class="small-buy-list-content" style="font-size:10px;">${clsStatus}</span></div>
                                    <div style="display:flex;margin:4px;"><span class="small-title">备注</span><span class="small-buy-list-content" style="font-size:8px;">${cmtStr}</span></div>
                                </div>
                                <div style="display:flex;justify-content:center;align-items:center;flex-grow:1;flex-direction:column; ">
                                    <img src="{{ url_for('static', filename='pics/logo_llz_for_page01.png') }}" alt="llzlogo" style="width:80px;height:auto;opacity: 0.86;">
                                    <div id=stage_${nn}></div>
                                    <div id=offsetAmount_${nn}></div>
                                    <div id=badge_${nn}></div>                                    
                                </div>                                
                            </div>
                            
                        `
                    buyList.appendChild(divRes);              
                    showCusStage(cusTotalAmount,nn);      
                    nn+=1;
                    }                    
                }

                const firstStageHint=document.createElement('div');
                firstStageHint.id='firstStageHint';
                firstStageHint.style.textAlign='center';
                buyList.appendChild(firstStageHint);
                showStageHints(cusTotalAmount);

                const buyPost=document.createElement('div');
                buyPost.innerHTML=`
                        <div style='margin-bottom:20px;margin-top:20px;text-align:center;'>—— 感谢你选择鹿鹿泽健身 ——</div>
                        <div style='text-indent:2em;font-size:10px;margin-bottom:50px;'>
                            <div>温馨提示：</div>
                            <div>
                                <p>1. <span style='font-weight:bold;'> 限时课程</span>如非因教练或工作室原因，须在有效期内上完，</p>       
                                <p><span style='font-weight:bold;font-size:11px;'>&nbsp;&nbsp;&nbsp;&nbsp;过期即失效，不可延期。</span></p>                         
                                <p>2. 请提前<span style='font-weight:bold;'> 24小时以上 </span>跟您的教练约课。</p>      
                                <p>3. 约课后如需取消预约或更改上课时间，</p>
                                <p>&nbsp;&nbsp;&nbsp;&nbsp;请提前<span style='font-weight:bold;'> 2小时以上 </span>与教练沟通确认。</span></p>  
                                <p>4. 训练前或训练过程中身体有任何不适，请立即告知教练。</p>
                                <p>5. 为了您的健身安全及舒适，请穿着运动服饰、运动鞋参加运动。</p>
                                <p>6. 为了您的健康及安全，运动前请不要饮酒或饮用含酒精类饮料。</p>
                                <p>7. 不要在健身工作室内吸烟。</p>
                                <p>8. 未经教练或工作人员许可，请不要携带宠物进入工作室。</p>
                            </div>

                        </div>
                    `
                buyList.appendChild(buyPost);

        
            }else{
                buyList.innerHTML='';
            }
           
            
        }


        function showValidSummary(data,ctnBuyData){
            const validSummaryBox=document.getElementById('validSummary');
            const cusIdName=document.getElementById('cusName').value.trim();
            validSummaryBox.innerHTML='';
            // validSummaryBox.id='validSummaryBox';
            //判断是否有效
            const today=new Date();
            today.setHours(0,0,0,0);
            
            let validArr=[];      

            for(const n in data){
                const sTime=new Date(data[n]['card_start_time']);
                sTime.setHours(0,0,0,0);
                const eTime=new Date(data[n]['end_time']);
                eTime.setHours(0,0,0,0);
                //有效的课程
                if(sTime<=today && eTime>=today && parseInt(data[n]['cls_qty'])-parseInt(data[n]['cls_tkn_qty'])>0){
                    validArr.push(data[n]);
                }           
            }
            
            console.log('valid arr:',validArr);

            //如果有有效的卡片
            if(validArr.length>0){
                const validTitle=document.createElement('div');
                validTitle.innerHTML=`会员目前有效的课程`;
                validTitle.style.fontWeight='bold';
                validTitle.style.color='#65a376';
                validTitle.style.fontSize='15px';
                validTitle.style.textAlign='center';
                validSummaryBox.appendChild(validTitle);
                

                validArr.forEach(card=>{
                    const div=document.createElement('div');
                    const showEndDate=new Date(card['end_time']);
                    showEndDate.setDate(showEndDate.getDate()-1);
                    if(card['buy_type']==='常规课程'){
                        if(card['buy_cls_name']==='活动赠课'){
                            div.innerHTML=`${card['card_id']}，${card['buy_type']} | ${card['buy_cls_name']}<br>有效期：${card['card_start_time']} 至 ${dateToString(showEndDate,'date')}，已上${card['cls_tkn_qty']}/${parseInt(card['cls_qty'])}节。`;
                        }else{
                            div.innerHTML=`${card['card_id']}，${card['buy_type']} | ${card['buy_cls_name']}<br>有效期：长期，已上${card['cls_tkn_qty']}/${parseInt(card['cls_qty'])}节。`;
                        }
                    }else if(card['buy_type']==='限时课程'){
                        div.innerHTML=`${card['card_id']}，${card['buy_type']} | ${card['buy_cls_name']}<br>有效期：${card['card_start_time']} 至 ${dateToString(showEndDate,'date')}，已上${card['cls_tkn_qty']}/${parseInt(card['cls_qty'])}节。`;
                    }else{
                        div.innerHTML=`${card['card_id']}，${card['buy_type']} | ${card['buy_cls_name']}<br>有效期：${card['card_start_time']} 至 ${dateToString(showEndDate,'date')}，已上${card['cls_tkn_qty']}/${parseInt(card['cls_qty'])}节。`;
                    }
                    div.classList.add('valid-inner-box');
                     
                    console.log('continue buy data:',ctnBuyData)
                    if(ctnBuyData && card['card_id']===ctnBuyData['data'][0]['card_id'] && ctnBuyData['latest_3_times_continue_buy']==='yes'){
            
                        const ctnBuyDiv=document.createElement('div');
                        ctnBuyDiv.innerHTML=`<span style='color:orange;font-size:10px;font-weight:bold;'>*连续购课三次</span>`;
                        div.appendChild(ctnBuyDiv);
                    }

                    validSummaryBox.appendChild(div);      
                });

                if(ctnBuyData){
                    showCtnList(validSummaryBox,ctnBuyData['data']);
                }else{
                    const noCtnDataDiv=document.createElement('div');
                    noCtnDataDiv.innerHTML='- 客户近期没有购买过限时课程 -';
                    noCtnDataDiv.style.textAlign='center';
                    noCtnDataDiv.style.fontSize='14px';
                    noCtnDataDiv.style.color='red';
                    noCtnDataDiv.style.padding='14px';
                    validSummaryBox.appendChild(noCtnDataDiv);
                }
                
                    // showCtnList(validSummaryBox,ctnBuyData['data']);

                const hr=document.createElement('hr');
                hr.style.marginTop='16px';
                hr.style.borderStyle='dotted';
                // hr.style.width='300px';
                
                validSummaryBox.appendChild(hr);
            }else{
                console.log('no valid cards, ctn data:',ctnBuyData)
                validSummaryBox.style.textAlign='center';
                validSummaryBox.innerHTML=`<span style='color:red;font-size:14px;'>- 客户目前已无有效课程 -</span>`;
                if(ctnBuyData && Object.keys(ctnBuyData['data'].length>0)){
                    showCtnList(validSummaryBox,ctnBuyData['data']);
                
                }else{
                    const noCtnDataDiv=document.createElement('div');
                    noCtnDataDiv.innerHTML='- 客户近期没有购买过限时课程 -';
                    noCtnDataDiv.style.textAlign='center';
                    noCtnDataDiv.style.fontSize='14px';
                    noCtnDataDiv.style.color='red';
                    noCtnDataDiv.style.padding='14px';
                    validSummaryBox.appendChild(noCtnDataDiv);
                }
                const hr=document.createElement('hr');
                hr.style.borderStyle='groove';
                // hr.style.width='300px';
                hr.style.marginTop='16px';
                validSummaryBox.appendChild(hr);
            }

        }

        function showCtnList(box,data){
            const latestBuyInfo=document.createElement('div');
            if(Object.keys(data).length<3){                
                latestBuyInfo.innerHTML=`近期共${Object.keys(data).length}条限时课购课记录`;
            }else{
                latestBuyInfo.innerHTML=`最近${Object.keys(data).length}次限时课程购课信息`;
            }


            latestBuyInfo.style.textAlign='center'; 
            latestBuyInfo.style.fontSize='14px';
            latestBuyInfo.style.color='#333d66';
            latestBuyInfo.style.marginTop='20px';
            box.appendChild(latestBuyInfo)            

            // if(Object.keys(data).length<3){
            //     latestBuyInfo.style.display='none';
            //     return;
            // }else{
            //     latestBuyInfo.style.display='block';
            // }

            for(i=0;i<Object.keys(data).length;i++){
                let ctnBuyColor='#f56642';
                const innerBox=document.createElement('div');
                innerBox.classList.add('ctn-inner-box');
                if(i<Object.keys(data).length-1){
                    if(data[i]['continue_buy']==='yes'){
                        ctnBuyColor='#75f542';
                    }
                    const cardId =document.createElement('div');
                    cardId.innerHTML=`卡号：${data[i]['card_id']} / 购于<span style='color:${ctnBuyColor};'> ${dateToString(data[i]['buy_date'],'dateDot')}</span>`;
                    const info=document.createElement('div');
                    const endDate=new Date(data[i+1]['end_time']);
                    endDate.setHours(0,0,0,0);
                    endDate.setDate(endDate.getDate()-1);
                    const delayStr=data[i+1]['real_days']-data[i+1]['buy_cls_days']<0?0:data[i+1]['real_days']-data[i+1]['buy_cls_days']
                    info.innerHTML=`上次课程结束于 ${dateToString(endDate,'dateDot')} / 共延期${delayStr}天`;
                    innerBox.appendChild(cardId);
                    innerBox.appendChild(info);
                }else{
                    const cardId =document.createElement('div');
                    cardId.innerHTML=`卡号：${data[i]['card_id']} / 购于<span style='color:#ffffff;'> ${dateToString(data[i]['buy_date'],'dateDot')}</span>`;
                    const info=document.createElement('div');
                    info.innerHTML=`上次课程结束日：-`;
                    innerBox.appendChild(cardId);
                    innerBox.appendChild(info);
                }
                box.appendChild(innerBox);
            }
        }


        function showNotOpenSummary(data){
            const notOpenSummaryBox=document.getElementById('notOpenSummary');
            const cusIdName=document.getElementById('cusName').value.trim();
            notOpenSummaryBox.innerHTML='';
            //判断是否有效      
            let notOpenArr=[]  

            for(const n in data){                
                if(data[n]['card_start_time']==='-' && data[n]['end_time']==='-'){
                    notOpenArr.push(data[n]);
                }
            }

            //如果有未开课卡片
            if(notOpenArr.length>0){
                const notOpenTitle=document.createElement('div');
                notOpenTitle.innerHTML=`会员未开课的限时课程`;
                notOpenTitle.style.fontWeight='bold';
                notOpenTitle.style.color='#5b8eb3';
                notOpenTitle.style.fontSize='15px';
                notOpenTitle.style.textAlign='center';
                notOpenSummaryBox.appendChild(notOpenTitle);
                

                notOpenArr.forEach(card=>{
                    const div=document.createElement('div');
                    div.style.textAlign='left';
                    div.innerHTML=`${card['card_id']}，${card['buy_type']} | ${card['buy_cls_name']}<br>购课日期：${dateToStringGmt(card['buy_date'],'date')}`;
                    div.style.fontSize='12px';
                    div.style.color='#5b8eb3';
                    div.style.border='1px solid #5b8eb3';
                    div.style.borderRadius='4px';
                    div.style.padding='6px';
                    div.style.marginTop='4px';
                    div.style.marginBottom='4px';                    
                    notOpenSummaryBox.appendChild(div);                    
                });

                const hr=document.createElement('hr');
                hr.style.marginTop='16px';
                hr.style.borderStyle='dotted';
                // hr.style.width='300px';
                notOpenSummaryBox.appendChild(hr);
            }else{
                notOpenSummaryBox.style.textAlign='center';
                notOpenSummaryBox.innerHTML='';
                // notOpenSummaryBox.innerHTML=`客户目前无未开课的限时课程`;
                // const hr=document.createElement('hr');
                // hr.style.borderStyle='dashed';
                // hr.style.marginTop='16px';
                // notOpenSummaryBox.appendChild(hr);
            }
        

        }



        function getBuyRec(idName){
            // console.log(idName)
            const buyListBox=document.getElementById('buyList');
            const dateBox=document.getElementById('dateBox');
            const dateSel=document.getElementById('dateSel');
            dateSel.innerHTML='';
            buyListBox.innerHTML='';

            const fetchData=fetch('/deal_show_cus_buyrec_lmtrec', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({"cusIdName":idName})
                })
                .then(response=>response.json())


            const fetchContinueBuyData=fetch('/get_cus_continue_buy', {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json'
                    },
                    body:JSON.stringify({'cusIdName':idName})
            })
            .then(response=>response.json())

            Promise.all([fetchData,fetchContinueBuyData])
            .then(([data,continueBuyData]) => {
                console.log('cus buy recs:',data)
                let ctnBuyData;
                if(continueBuyData['res']==='ok'){
                    // console.log('continue buy data:',continueBuyData);
                    ctnBuyData=continueBuyData;
                }else{
                    ctnBuyData=undefined;
                }

                if(data['res']==='ok'){
                    showValidSummary(data['data'],ctnBuyData);
                    showNotOpenSummary(data['data']);
                    buyData=data['data'];
                    dateBox.style.display='flex';
                    let dateArr=[];          
                    for(const n in data['data']){
                        if(!dateArr.includes(dateToStringGmt(data['data'][n]['buy_date'],'date'))){
                            dateArr.push(dateToStringGmt(buyData[n]['buy_date'],'date'));
                        }
                    }


                    // 使用自定义比较函数对日期进行降序排列
                    dateArr.sort((a, b) => {
                    // 将日期字符串转换为日期对象
                    const dateA = new Date(a);
                    const dateB = new Date(b);

                    // 返回比较结果
                    return dateB - dateA;
                    });

                    dateArr.forEach(item=>{                 
                        const opt=document.createElement('option');
                        opt.value=item;
                        opt.text=item;                            
                        dateSel.appendChild(opt);                               
                    });
                    
                    dateSel.addEventListener('change',showBuyRecDetail);
                    const eve=new Event('change');
                    dateSel.dispatchEvent(eve);                        

                }else{
                    dateBox.style.display='none';
                    buyListBox.innerHTML='未查询到该会员的购课记录';

                }


                

                })
            .catch(error => console.error('Error:', error));
        }

        async function handleInput() {
            // 获取输入框中的值
            const searchTerm = document.getElementById("cusName").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusList");
            const buyListBox=document.getElementById('buyList');
            const validSummary=document.getElementById('validSummary');
            const notOpenSummary=document.getElementById('notOpenSummary');
            validSummary.innerHTML='';
            notOpenSummary.innerHTML='';
            buyListBox.style.display='none';

            document.getElementById('dateBox').style.display='none';

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", async function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusName").value = name;
                        getBuyRec(name);
                        resultList.style.display = "none";
                        resultList.innerHTML = "";
                        buyListBox.style.display='flex';
                        buyListBox.style.flexDirection='column';
                        
                        try {
                            // 使用 await 获取返回值
                            const totalAmount = await getCusBuySum(name);
                            cusTotalAmount = totalAmount;
                            console.log('cusTotalAmount:', cusTotalAmount);
                            // 在这里可以使用 cusTotalAmount 做后续操作
                        } catch (error) {
                            console.error('获取会员总购课金额错误：', error);
                            cusTotalAmount = 0;
                        }

                        // get_cus_continue_buy();
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);

                                 

                    
                }else{
           

                }
            });
        
            resultList.classList.add("cus-list-result-show");
            resultList.style.top='138px';
            resultList.style.left='214px';
            
        }

    function getCusBuySum(name){
        return fetch(`/get_cus_buy_sum?cus_id=${encodeURIComponent(name.slice(0,7))}`)
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){
                    console.log('get cus buy sum data:',data);
                    return parseFloat(data.data[0]['total_amount']);
                } else {
                    throw new Error(data.msg || '获取会员总购课金额失败');
                }                     
            })
            .catch(error=>{
                console.log('获取会员总购课金额错误：',error);
                throw error;
            });  
        }                

    </script>
    
</body>
